package station;

/**
 * Vorlesung: Verteilte Systeme
 * Aufgabe  : 04
 * 
 * @author Benjamin Burchard
 * @author Tell Mueller-Pettenpohl
 * 
 */

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class DataMessage {

    public static final byte MESSAGE_SIZE = 33;
    public static final byte DATA_LENGTH = 24;
    public static final byte NEXT_SLOT_BYTE = 24;
    public static final byte TIME_LENGTH = 8;

    /**
     * Compresses the given Parameters to the requestet Packet-Size
     * 
     * @param data
     *            userdata
     * @param nextslot
     *            next slot to use
     * @param timestamp
     *            synchronized timestamp
     * @return The new byte[] packet
     */
    public static byte[] packMessage(byte[] data, byte nextslot, long timestamp) {
        ByteBuffer msgBuffer = ByteBuffer.allocate(MESSAGE_SIZE);
        msgBuffer.order(ByteOrder.LITTLE_ENDIAN);
        msgBuffer.put(data, 0, data.length).put(data.length + 1, nextslot)
                .putLong(data.length + nextslot + 1, timestamp);
        return msgBuffer.array();
    }

    /**
     * Retrieves the timestamp out of the given packet
     * 
     * @param packet
     *            to get the timestamp of
     * @return a long timestamp
     */
    public static long getTime(byte[] packet) {
        if (packet.length != MESSAGE_SIZE) {
            throw new IllegalArgumentException("Package size wrong by "
                    + (MESSAGE_SIZE - packet.length) + " bytes");
        }
        ByteBuffer msgBuffer = ByteBuffer.allocate(MESSAGE_SIZE);
        msgBuffer.order(ByteOrder.LITTLE_ENDIAN);
        msgBuffer.put(packet, NEXT_SLOT_BYTE + 1, TIME_LENGTH);
        return msgBuffer.getLong(0);
    }

}
